package com.welike.shibo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.welike.shibo.eneity.Audio;
import com.welike.shibo.eneity.JsonResult;
import com.welike.shibo.enums.ResultEnum;
import com.welike.shibo.mapper.AudioMapper;
import com.welike.shibo.service.AudioService;
import com.welike.shibo.service.RedisService;
import com.welike.shibo.utils.*;
import com.welike.shibo.vo.page.AudioPageVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.welike.shibo.utils.Constants.REDIS_UPLOAD_KEY;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2019-08-20 00:40
 */

@Slf4j
@Service
public class AudioServiceImpl extends ServiceImpl<AudioMapper, Audio> implements AudioService {

    @Autowired
    private AudioMapper audioMapper;

    @Autowired
    private RedisService redisService;

    @Value("${media.path}")
    private String MEDIA_PATH;

    // 查询所有Audio(后台)
    @Override
    public IPage<Audio> queryAllAudio(Integer page, Integer pageSize) {
        Page<Audio> p = new Page<>(page, pageSize);
        return audioMapper.queryAllAudio(p);
    }

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        // 获取文件名
        String originalFileName = file.getOriginalFilename();
        String upload_key = REDIS_UPLOAD_KEY + "task";
        // 获取文件后缀
        String prefix = originalFileName.substring(originalFileName.lastIndexOf("."));
        FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
        FileOutputStream fileOutputStream = null;
        QiNiuUtil qiNiuUtil = new QiNiuUtil();
        String fileName = Tools.getYearMonth() + System.currentTimeMillis() + prefix;

        String mp3OutputPath = MEDIA_PATH + "/media/mp3/" + fileName;
        File outFile = new File(mp3OutputPath);
        if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
            //创建父文件夹
            outFile.getParentFile().mkdirs();
        }
        fileOutputStream = new FileOutputStream(outFile);
        IOUtils.copy(fileInputStream, fileOutputStream);
        log.info("上传存放路径: ==> {}", mp3OutputPath);
        JSONObject task = new JSONObject();
        task.put("name", fileName);
        task.put("path", mp3OutputPath);
        redisService.lpush(upload_key, task.toJSONString());
        return fileName;
//        return qiNiuUtil.uploadQiNiu(fileInputStream, fileName);
    }

    /**
     * 获取
     * @param page
     * @param pageSize
     * @param state
     * @return
     */
    @Override
    public IPage<AudioPageVo> selectAudioPageVo(Integer page, Integer pageSize, Integer state) {
        try {
            Page<AudioPageVo> p = new Page<>(page, pageSize);
            audioMapper.selectAudioPageVo(p, state);
            return p;
        } catch (RuntimeException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public String queryNameById(String aid) {
        return audioMapper.queryNameById(aid);
    }

    @Override
    public JsonResult uploadMusic(MultipartFile file, String name, Integer duration) throws IOException {
        if (file == null||name == null|| duration == null){
            return ResultUtils.error("字段不可为空!");
        }
        String url = uploadFile(file);
        Audio audio = new Audio();
        audio.setId(Tools.getUniqueKey());
        audio.setName(name);
        audio.setAudioUrl(url);
        audio.setDuration(duration);
        audio.setStatus(1);
        audio.setCreateTime(new Date());
        if (audioMapper.insert(audio) == 1){
            Map<String, Object> map = new HashMap<>();
            map.put("audio", audio);
            return ResultUtils.success("成功添加!", map);
        }else {
            return ResultUtils.error("添加失败");
        }
    }

    @Override
    public String queryAudioUrlById(String audioId) {
        return audioMapper.queryAudioUrlById(audioId);
    }

    @Override
    public JsonResult addMusic(JSONObject requestJson) {
        CommonUtil.hasAllRequired(requestJson, "music, name");
        String id = Tools.getUniqueKey();
        String music = requestJson.getString("music");
        String name = requestJson.getString("name");
        Integer duration = requestJson.getIntValue("duration");
        int result = audioMapper.addMusic(id, music, name, duration);
        if (result == 1){
            return ResultUtils.success("更新成功!");
        } else {
            return ResultUtils.error("更新失败!");
        }
    }

    @Override
    public JsonResult deleteMusicById(String id) {
        if (id == null && StringTools.isNullOrEmpty(id)){
            return ResultUtils.error(ResultEnum.E_90003);
        }
        int result = audioMapper.deleteById(id);
        if (result == 1){
            return ResultUtils.success("删除成功!");
        } else {
            return ResultUtils.error("删除失败!");
        }
    }

    @Override
    public JsonResult updateStatus(String id, String status) {
        if (StringTools.isNullOrEmpty(id) || StringTools.isNullOrEmpty(status)){
            return ResultUtils.error(ResultEnum.E_90003);
        }
        int result = audioMapper.updateStatus(id, status);
        if (result == 1){
            return ResultUtils.success("更新成功!");
        } else {
            return ResultUtils.error("更新失败!");
        }
    }
}
